package com.ky.pro.java.jvm;

import java.lang.reflect.Method;

/**
 * @ClassName XlassLoaderApp
 * @Description TODO
 * @Date 2021/11/6 16:37
 * @Author kevin
 **/
public class XlassLoaderApp {

    public static void main(String[] args) {

        try {
            // 使用自定义类加载器加载
            XlassLoader xlassLoader = new XlassLoader();
            Class<?> helloClaz = xlassLoader.loadClass("Hello");

            // 打印加载完成的类信息
            dumpClassInfo(helloClaz);

            System.out.println("Trying to invoke hello method: ");
            // 创建实例并调用方法
            Object helloObj = helloClaz.getDeclaredConstructor().newInstance();
            helloClaz.getDeclaredMethod("hello").invoke(helloObj);
            System.out.println();

            // 尝试加载一个不存在的类，抛出异常
            Class<?> wrongClaz = xlassLoader.loadClass("World");
            dumpClassInfo(wrongClaz);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void dumpClassInfo(Class<?> claz) {
        System.out.println("Declared methods of class " + claz.getName() + ":");
        for (Method method : claz.getDeclaredMethods()) {
            System.out.println(method.getName());
        }
        System.out.println();
    }

}
